package utils;
/**
 * ByteUtil is a util class which is used to operate a byte array.
 * @author Jie Zhao(288654)
 *
 */
public class ByteUtil {
	/**
	 * print a byte array in form of Hex string
	 * @param b
	 */
	public static void printByteArray(byte[] b)
	{
		int count = 0;
		for(byte bb : b)
		{
			System.out.print(Integer.toHexString(bb));
			if(++count < b.length)System.out.print(":");
		}
		System.out.println();
	}
	/**
	 * fill a byte array with a integer
	 * @param b
	 * @param start
	 * @param number
	 */
	public static void fillByteArray(byte[] b,int start,int number)
	{
		if(b == null || start+(Integer.SIZE/Byte.SIZE) > b.length)return;
		for(int i=0;i<(Integer.SIZE/Byte.SIZE);i++)
		{
			//System.out.println(((Integer.SIZE/Byte.SIZE -i-1)*Byte.SIZE));
			b[i+start] = (byte)(number >> ((Integer.SIZE/Byte.SIZE -i-1)*Byte.SIZE));
		}
	}
	/**
	 * parse a byte array to an integer
	 * @param b
	 * @param start
	 * @return
	 */
	public static int parseInt(byte[] b, int start)
	{
		if(b == null || b.length < start+(Integer.SIZE/Byte.SIZE))return 0;
		else
		{
			int result = 0;
			int size = Integer.SIZE/Byte.SIZE;
			for(int i=0;i<size;i++)
			{
				result += (0xff << ((size-i-1)*Byte.SIZE)) &(b[i+start] << ((size-i-1)*Byte.SIZE));
			}
			return result;
		}
	}
	
	public static void main(String[] args) {
		int i = 1000000000;
		byte[] b = new byte[Integer.SIZE/Byte.SIZE];
		System.out.println(Integer.toHexString(i));
		fillByteArray(b, 0, i);
		printByteArray(b);
		System.out.println(Integer.toHexString(parseInt(b, 0)));
	}
}
